package editor.widgets;

import observer.BooleanObserver;
import observer.ObservedBoolean;

import javax.swing.*;
import javax.swing.event.AncestorListener;
import javax.swing.event.AncestorEvent;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * This is a {@link JCheckBox} that automatically updates the {@link ObservedBoolean} that it manages,
 * so that the model is updated properly.

 * FIXME: This doesn't support being updated from outside the widget (e.g. undos) like {@link ObservedStringField} does.
 *
 * @author Neil Dickson
 */
public class ObservedBooleanCheckBox extends JCheckBox implements BooleanObserver, ActionListener, AncestorListener {
	private ObservedBoolean value;

	public ObservedBooleanCheckBox(ObservedBoolean value,String text) {
		super(text,value.get());
		this.value = value;
		value.addObserver(this);
		addActionListener(this);
		addAncestorListener(this);
	}

	public void valueChanged(ObservedBoolean b) {
		setSelected(b.get(),false);
	}

	public void setSelected(boolean b,boolean updateValue) {
		super.setSelected(b);
		if (updateValue) {
			value.set(this,b);
		}
	}

	public void setSelected(boolean b) {
		setSelected(b,true);
	}

	public void actionPerformed(ActionEvent e) {
		value.set(this,isSelected());
	}

	public void setBackground(Color bg) {
		super.setBackground(bg);
		setOpaque(bg.getAlpha()==255);
	}

	public void ancestorAdded(AncestorEvent event) {
		value.addObserver(this);
	}

	public void ancestorRemoved(AncestorEvent event) {
		value.removeObserver(this);
	}

	public void ancestorMoved(AncestorEvent event) {}
}
